'use strict';
import React, {
    Component,
    PropTypes
} from 'react';
import ReactDOM, {
    render
} from 'react-dom';

import {
    HttpService,
    Toast,
    GetCurrentDate
} from '../Http';
import {
    Tool
} from '../utils';
import {
    doLogin,
    change,
    getOneBabyid,
    changeSaveBabyStatus,
    getMap,
    getCurrentPower,
    exportMap
} from '../action/index'

import {
    connect
} from 'react-redux';
import {
    bindActionCreators
} from 'redux';

import Link from './common/Link'
import '../less/index.less'

import '../less/deviceList.less'

import usrimg from '../img/user.png'

import qiehuan from '../img/qiehuan.png'

import dian2 from '../img/dianliang1.png'
import dian3 from '../img/dianliang2.png'
import dian4 from '../img/dianliang3.png'
import dian1 from '../img/didianliang.png'
import dian from '../img/lixian.png'

import lishiguiji from '../img/lishigj2.png'
import banji from '../img/banji.png'

import wifi from '../img/wifi.png'
import lbs from '../img/lbs.png'
import gbs from '../img/gps.png'

import touxiang from '../img/touxiang.png'

import shouqi from '../img/shouqi.png'

import dingweixiao from '../img/dingweixiao.png'
import dingwei from '../img/dingwei.png'
import tongzhi from '../img/jianhuchengyuan.png'

import tonghuaxiao from '../img/tonghuaxiao.png'
import downa from '../img/downa.png'
import buydev from '../img/tianjia.png'

import zhankai from '../img/zhankai.png'

import tonghua from '../img/tonghua.png'

import anquan from '../img/anquan.png'

import more from '../img/more.png'

import guanbi from '../img/guanbi.png'

import header from '../img/login/header.jpg'
import footer from '../img/login/footer.jpg'

import jianhuchengyuan from '../img/jianhuchengyuan.png'

import genghuan from '../img/genghuan.png'

import jiebang from '../img/jiebang.png'

import kaoqin from '../img/kaoqin.png'
import imgKan from '../img/kan.png'
import imgguiji from '../img/lishiguiji.png'

import Model from './common/model'

class MapIndex extends React.Component {

    static contextTypes = {
        router: React.PropTypes.object.isRequired
    };

    static defaultProps = {
        authstatus: 'li'
    };

    constructor(props) {
        super(props);
        this.state = {
            lng: '120.153576',
            lat: '30.287459',
            isOpen: false,
            mapHeight: '100%',
            mapBottom: '4.5rem',
            checked: false,
            babyname: '',
            babyid: '',
            deviceType: '',
            model: {},
            babyInfo: {},
            is: false,
            getThirdPartyFlag: false,
            isReceiveProps: false
        };
        this.modelConfigBabyNone = {
            model_content_contnet: true,
            header: <div className="header">
                <img src={header} className="app-all-img"/>
            </div>,
            content: <div className="content">
                <div className="_header"></div>
                <div className="_content">
                    无设备提醒
                </div>
                <Link to={'/addDevice'}>
                    <div className="_footer app-active-font32">去添加</div>
                </Link>
            </div>,
            footer: <div className="footer">
                    <img src={footer} className="app-all-img"/>
                </div>

        };

        this.modelConfigBabyState0 = {
            model_content_contnet: true,
            header: <div className="header">
                <img src={header} className="app-all-img"/>
            </div>,
            content: <div className="content app-padding-lr20">
                <div className="_header app-active-font32">
                    实名认证
                </div>
                <div className="_content step app-666-font24" style={{
                    flexDirection: 'column'
                }}>
                    <div>尊敬的学生家长</div>
                    <div>根据国家工信部电话实名制要求，为保证智能学生证正常使用，请根据提示即时进行认证！为此给您带来的不便敬请谅解，感谢您的支持！</div>
                </div>
                <div className="_footer step">
                    <div className="s-flex1 s-j-end app-666-font32" onClick={this.no.bind(this)}>下次提醒</div>
                    <div className="app-padding-lr50"></div>
                    <div className="s-flex1 app-active-font32" onClick={this.authen.bind(this)}>去认证</div>
                </div>
            </div>,
            footer: <div className="footer">
                    <img src={footer} className="app-all-img"/>
                </div>
        };

        this.modelConfigBabyState1 = {
            model_content_contnet: true,
            header: <div className="header">
                <img src={header} className="app-all-img"/>
            </div>,
            content: <div className="content app-padding-lr20">
                <div className="_header app-active-font32">
                    实名认证
                </div>
                <div className="_content step app-666-font24" style={{
                    flexDirection: 'column'
                }}>
                    <div>您的实名认证正在审核中，我们会尽快为您处理，请耐心等待</div>
                </div>
                <div className="_footer step">
                    <div className="s-center app-active-font32" onClick={this.no1.bind(this)}>我知道了</div>
                </div>
            </div>,
            footer: <div className="footer">
                    <img src={footer} className="app-all-img"/>
                </div>
        };

        this.modelConfigBabyState2 = {
            model_content_contnet: true,
            header: <div className="header">
                <img src={header} className="app-all-img"/>
            </div>,
            content: <div className="content app-padding-lr20">
                <div className="_header app-hong-font32">
                    实名认证未通过
                </div>
                <div className="_content step app-666-font24" style={{
                    flexDirection: 'column'
                }}>
                    <div>姓名和身份证不匹配，身份证正面照片不合格，身份证反面照片不合格</div>
                </div>
                <div className="_footer step">
                    <div className="s-flex1 s-j-end app-666-font32" onClick={this.no2.bind(this)}>下次提醒</div>
                    <div className="app-padding-lr50"></div>
                    <div className="s-flex1 app-active-font32" onClick={this.authen.bind(this)}>去认证</div>
                </div>
            </div>,
            footer: <div className="footer">
                    <img src={footer} className="app-all-img"/>
                </div>
        }
        this.modelConfigBabyState3 = {
            model_content_contnet: true,
            header: <div className="header">
                <img src={header} className="app-all-img"/>
            </div>,
            content: <div className="content app-padding-lr20">

                <div className="_header app-active-font32">
                    实名认证
                </div>
                <div className="_content step app-666-font24" style={{
                    flexDirection: 'column'
                }}>
                    <div>因设备逾期未进行实名认证，现已无法正常使用，请联系设备管理员进行实名认证</div>
                </div>
                <div className="_footer step">
                    <div className="s-center app-active-font32" onClick={this.no3.bind(this)}>我知道了</div>
                </div>
            </div>,
            footer: <div className="footer">
                    <img src={footer} className="app-all-img"/>
                </div>
        }
    }

    no() {
        this.setState({
            model: Tool.assign({}, this.state.model, {
                flag: false
            })
        })
    }

    no1() {
        this.setState({
            model: Tool.assign({}, this.state.model, {
                flag1: false
            })
        })
    }

    no2() {
        this.setState({
            model: Tool.assign({}, this.state.model, {
                flag2: false
            })
        })
    }

    no3() {
        this.setState({
            model: Tool.assign({}, this.state.model, {
                flag3: false
            })
        })
    }
    noFn() {
        Toast.toast('当前设备不支持此功能<br/>请升级为智能学生证后使用');
    }
    authen() {
        this.context.router.push('/authen/' + this.state.babyInfo.telephone)
    }
    appDown() {
        localStorage.appdown = 1;
        localStorage.goback = 1;
        location.href = 'http://www.17find.com/download/?from=weixin02'
    }
    componentWillMount() {
        if (this.props.params.token == undefined) {
            Toast.toast('对不起，你访问的页面不存在', 0);
            return;
        }

        if (this.props.params.userid == undefined && this.props.babyid == '') {
            localStorage.clear();
            localStorage.appToken = this.props.params.token;
            this.props.getOneBabyid();
            return;
        }
        if (localStorage.delDevice == 1 || localStorage.goback == 1) {
            this.props.getOneBabyid();
            localStorage.goback = 0;
        } else if (!!this.props.babyid) {
            this.props.getMap(this.props.babyid, this.props.deviceType, true)
        }
    }

    componentWillUnmount() {
        if (this.props.exportMap.length != 0) {
            this.props.exportMap.clearMap();
        }
        var node = document.getElementById('container');
        if (!!node.parentNode) {
            node.parentNode.removeChild(node);
        }
        localStorage.delDevice = 0;
    }
    /**
     * map页面加载完后--加载百度统计点击事件
     */
    componentDidMount() {
        if (this.props.params.token == undefined) {
            document.getElementById('totalpeal').style.display = 'block';
        }
        this.getBaby(this.props.babyid);
    }

    _change(babyname, babyid, deviceType, authstatus, headimg, babytelephone, e) {
        localStorage.is = 0;
        e.preventDefault();
        this.setState({
            checked: false,
            deviceType: deviceType
        });
        localStorage.babyid = babyid;
        const data = {
            babyname,
            authstatus,
            babyid,
            babytelephone,
            headimg,
            deviceType
        };
        this.props.change(data);
        this.getBaby(babyid);
    }

    more() {
        this.setState({
            checked: true
        })
    }

    guanbi() {
        this.setState({
            checked: false
        })
    }

    changeAge(f) {
        HttpService.query({
            url: '/app/object/modifyBabyInfo',
            data: {
                familystatus: f,
                babyid: this.props.babyid,
                token: localStorage.appToken,
                weixinclient: 'true'
            },
            success: (res => {
                if (res.code == '10042') {
                    Toast.toast(res.msg);
                    this.props.changeSaveBabyStatus(false);

                    if (localStorage.publicLink == 'true') {
                        delete localStorage.publicLink
                        this.context.router.push('/App/' + localStorage.babyid)
                    }

                } else {
                    Toast.toast(res.msg);
                }
            })
        })

    }


    //过期提示判断，认证判断，无设备ID判断
    packageExpired(url, url2, e) {
        if (this.state.babyInfo.deviceType == 3) {
            e.preventDefault();
            Toast.toast('当前设备不支持此功能<br/>请升级为智能学生证后使用');
            return;
        }
        if (this.authstatusTip(this.state.babyInfo, 1) == 1) {
            e.preventDefault();
            return;
        }
        let nowTime = new Date();
        let month = nowTime.getMonth() + 1;
        if (month < 10)
            month = '0' + month;
        nowTime = new Date(nowTime.getFullYear() + '/' + month + '/' + nowTime.getDate())
        let getTime = new Date(this.state.babyInfo.endTime);
        if ((nowTime.getTime() - getTime.getTime()) / 1000 > 0) {
            Toast.toast('当前设备套餐已过期<br/>请缴费后使用');
            if (url2 == 'tel') {
                e.preventDefault();
            }
        } else {
            if (url2 == 'tel') {
                return;
            }
            if (url2 == 'getLocation') { //定位处理
                this.props.getMap(this.props.babyid, this.state.deviceType);
                return;
            }
            this.context.router.push(url2);
        }
    }

    getBaby(id) {
        if (localStorage.appToken == undefined)
            return;
        if (!id)
            id = localStorage.babyid;
        if (!id) {
            setTimeout(() => {
                this.getBaby()
            }, 400)
            return
        }
        HttpService.query({
            url: '/app/object/getBabyJxt',
            data: {
                token: localStorage.appToken,
                babyid: id,
                weixinclient: 'true'
            },
            success: (res => {
                if (res.code == '10038') {
                    this.setState({
                        babyInfo: {
                            mdtid: res.data.mdtid,
                            telephone: res.data.telephone,
                            endTime: res.data.endtime,
                            babyname: res.data.babyname,
                            userid: res.data.userid,
                            isadmin: res.data.isadmin,
                            authstatus: res.data.authstatus,
                            deviceType: res.data.deviceType,
                            headimg: res.data.headimg,
                            babytelephone: res.data.babytelephone,
                            babyid: res.data.babyid
                        },
                        deviceType: res.data.deviceType
                    });
                    this.authstatusTip(res.data);
                }
            })
        })
    }

    authstatusTip(babyInfo, packageExpired) {
        if (babyInfo.deviceType == 2) {
            if (packageExpired != 1) {
                if (localStorage.authstatus && localStorage.authstatus.indexOf(babyInfo.babyid) > -1)
                    return 0;
            }
            if (localStorage.authstatus == undefined)
                localStorage.authstatus = '';
            if (babyInfo.isadmin == true) {
                localStorage.is = 1;
                localStorage.authstatus += babyInfo.babyid + ',';
                if (babyInfo.tianyin == true && babyInfo.authstatus != 3) {
                    this.setState({
                        model: Tool.assign({}, this.state.model, {
                            flag4: true
                        })
                    })
                    return 1;
                }
                if (babyInfo.authstatus == 0) {
                    this.setState({
                        model: Tool.assign({}, this.state.model, {
                            flag: true
                        })
                    });
                    return 1;
                } else if (babyInfo.authstatus == 1) {
                    this.setState({
                        model: Tool.assign({}, this.state.model, {
                            flag1: true
                        })
                    });
                    return 1;
                } else if (babyInfo.authstatus == 2) {
                    this.setState({
                        model: Tool.assign({}, this.state.model, {
                            flag2: true
                        })
                    });
                    return 1;
                }
            } else {
                if (babyInfo.authstatus == 0) {
                    localStorage.is = 1;
                    localStorage.authstatus += babyInfo.babyid + ',';
                    this.setState({
                        model: Tool.assign({}, this.state.model, {
                            flag3: true
                        })
                    });
                    return 1;
                }
            }
        }
    }
    componentWillReceiveProps(nextProps, nextState) {
        if (this.state.isReceiveProps && localStorage.delDevice != 1)
            return;
        this.setState({
            isReceiveProps: true
        });
        // if (localStorage.is == 0)
        //     this.getBaby(this.props.babyid);
    }

    shouldComponentUpdate(nextProps, nextState) {
        return true;
    }

    render() {
        const getCurrenttime = GetCurrentDate.time();
        const {
            babyInfo
        } = this.state;
        const {
            babyName,
            babytelephone,
            list,
            authstatus,
            headimg,
            values,
            lng,
            lat,
            gpstime,
            getGuardiansList,
            _checked,
            relationList,
            address,
            isLogin,
            datasource
        } = this.props;
        const babyid = this.props.babyid;
        var isOpen = this.state.isOpen;
        var mapHeight = this.state.mapHeight;
        const mapBottom = this.state.mapBottom;
        const checked = this.state.checked;

        let valueType = () => {
            if (this.props.deviceType == 3)
                return;
            if (values == '0') {
                return <img src={dian} className='dianchi'/>
            } else if (values == '1') {
                return <img src={dian1} className='dianchi'/>
            } else if (values == '2') {
                return <img src={dian2} className='dianchi'/>
            } else if (values == '3') {
                return <img src={dian3} className='dianchi'/>
            } else if (values == '4') {
                return <img src={dian4} className='dianchi'/>
            }
        };

        let listItem = list.map((json, index) => {
            return (
                <div className="device-info" key={index} onClick={this._change.bind(this, json.babyname, json.babyid, json.deviceType, json.authstatus, json.headimg, json.babytelephone)}>
                    <div className="headimg">
                        {!json.headimg
                            ? <img src={touxiang}/>
                            : <img src={"/media" + json.headimg}/>
}
                    </div>
                    <div className="info">
                        <div className="name">{json.babyname}</div>
                        <div className="time">设备套餐有效期：{json.deviceType != 3&&json.endtime
                                ? json.endtime.replace(/\-/g, '.')
                                :'永久有效' }</div>
                    </div>
                </div>
            )
        });

        const {
            model
        } = this.state;
        const {
            deviceType
        } = this.props
        return (
            <div>
                {checked == true
                    ? <div>
                            <div className="_z"></div>
                            <div className="layer_content">
                                <div className="header">
                                    <div className="left"></div>
                                    <div className="title">我的设备</div>
                                    <div className="guanbi"><img src={guanbi} style={{
                            width: '2.2rem'
                        }} onClick={this.guanbi.bind(this)}/></div>
                                </div>
                                <div className="layer_content2">
                                    {listItem}
                                </div>
                            </div>
                        </div>
                    : null
}

                <Model modelConfig={this.modelConfigBabyNone} flag={_checked}/>
                <Model modelConfig={this.modelConfigBabyState0} flag={model.flag}/>
                <Model modelConfig={this.modelConfigBabyState2} flag={model.flag2}/>
                <Model modelConfig={this.modelConfigBabyState1} flag={model.flag1}/>
                <Model modelConfig={this.modelConfigBabyState3} flag={model.flag3}/> {deviceType == 3
                    ? <div className='maptips'>
                            <img className='kan' src={imgKan}/>
                            <div>当前设备仅支持一般考勤功能</div>
                        </div>
                    : ''
}
                {!!relationList
                    ? <div>
                            <div className="_zz"></div>
                            <div className="layer_content3">
                                <div className="header">
                                    <div className="title">选择成员关系</div>
                                </div>
                                <div className="layer_content4">
                                    {getGuardiansList.map((json, index) => {
                                        return <div className="row" key={index} onClick={this.changeAge.bind(this, json.familystatus)}>
                                            <div className="left">
                                                {json.check == true
                                                    ? <img src={json.img1}/>
                                                    : <img src={json.img}/>
}
                                            </div>
                                            <div className="right">
                                                {json.title != '家庭'
                                                    ? <div className="one">我是{json.familystatus}</div>
                                                    : <div className="one">{json.familystatus}</div>
}
                                                <div className="two">{json.ds}</div>
                                            </div>
                                        </div>
                                    })
}
                                </div>

                            </div>

                        </div>
                    : null
}

                <div className="box">
                    <div className="box1">

                        {!headimg
                            ? <img src={touxiang} style={{
                                    width: '3.4rem',
                                    height: '3.4rem'
                                }}/>
                            : <img src={"/media" + headimg} style={{
                                width: '3.4rem',
                                height: '3.4rem'
                            }}/>
}
                    </div>
                    <div className="box2">
                        <div className="babyName">
                            <span className="row1">{deviceType == 3
                                    ? '无法获取' + babyName + '当前位置'
                                    : babyName}
                            </span>
                            {deviceType == 3
                                ? ''
                                : <span className="row2">[最后上报位置]&nbsp;</span>}

                            {deviceType == 2
                                ? datasource == 1
                                    ? <img src={gbs} style={{
                                            width: '1.2rem'
                                        }}/>
                                    : datasource == 2
                                        ? <img src={wifi} style={{
                                                width: '1.2rem'
                                            }}/>
                                        : datasource == 3
                                            ? <img src={lbs} style={{
                                                    width: '1.2rem'
                                                }}/>
                                            : ''
                                : ''}

                            {valueType()
}

                        </div>

                        <div className="address">
                            <div className="ss">

                                {deviceType == 2
                                    ? !gpstime
                                        ? <span>{getCurrenttime + ' '}</span>
                                        : gpstime + ' '
                                    : ''
}
                                {!address
                                    ? <span>{deviceType == 3
                                                ? <span style={{
                                                        color: 'red'
                                                    }}>当前设备不支持实时定位</span>
                                                : '未获取到当前设备定位!'}</span>
                                    : <span>
                                        {address}</span>
}
                            </div>
                        </div>
                    </div>
                    <div className="box3" onClick={this.more.bind(this)}>
                        <img src={qiehuan} style={{
                            width: '2.2rem'
                        }}/>
                    </div>
                </div>
                {/*<div className="app-kuiji">
                    <Link to={'/path/' + babyid + '/' + lng + '/' + lat + ''}>
                        <img src={lishiguiji} style={{
                            width: '2.8rem'
                        }}/>
                    </Link>
                </div>*/}
                <div id="container"></div>
                <div className="menu menumap">
                    <div className="option" onClick={this.packageExpired.bind(this, '/shengji/dingwei', 'getLocation')}>
                        <img src={dingwei}/>
                        <div>实时定位</div>
                    </div>
                    <div className="option">
                        <a href={"tel:" + babytelephone} onClick={this.packageExpired.bind(this, '/shengji/tonghua', 'tel')}>
                            <img src={tonghua}/>
                            <div>亲情通话</div>
                        </a>
                    </div>
                    <div className="option">
                        <Link to={'/Kaoqin/' + babyid}>
                            <img src={kaoqin}/>
                            <div>考勤</div>
                        </Link>
                    </div>
                    <Link className="option" to='/addDevice'>
                        <img src={buydev} style={{
                            width: '2.3rem',
                            height: '2.3rem'
                        }}/>
                        <div>添加设备</div>
                    </Link>
                    <div className="option">
                        <div onClick={this.packageExpired.bind(this, '/shengji/anquan', '/Safetyarea/' + babyid)}>
                            <img src={anquan}/>
                            <div>安全区域</div>
                        </div>
                    </div>
                    <div className="option">
                        <Link to={'/Guardian/' + babyid}>
                            <img src={tongzhi}/>
                            <div>成员管理</div>
                        </Link>
                    </div>
                    <div className="option">
                        <div onClick={this.packageExpired.bind(this, '/shengji/anquan', '/path/' + babyid + '/' + lng + '/' + lat)}>
                            <img src={imgguiji}/>
                            <div>历史轨迹</div>
                        </div>
                    </div>
                    <div className="option">
                        <Link to={'/More/' + babyid}>
                            <img src={more}/>
                            <div>更多</div>
                        </Link>
                    </div>
                </div>
            </div>
        )
    }

}

const mapStateToProps = state => {
    return {
        list: state.login.list,
        babyName: state.login.babyName,
        babyid: state.login.babyid,
        authstatus: state.login.authstatus,
        babytelephone: state.login.babytelephone,
        headimg: state.login.headimg,
        values: state.login.values,
        lng: state.login.lng,
        lat: state.login.lat,
        gpstime: state.login.gpstime,
        getGuardiansList: state.login.getGuardiansList,
        _checked: state.login.checked,
        relationList: state.login.relationList,
        address: state.login.addr,
        datasource: state.login.datasource,
        isLogin: state.login.isLogin,
        exportMap: state.login.exportMap,
        deviceType: state.login.deviceType
    };
};
const mapDispatchToProps = (dispatch) => {
    return bindActionCreators({
        doLogin: doLogin,
        change: change,
        getOneBabyid: getOneBabyid,
        changeSaveBabyStatus: changeSaveBabyStatus,
        getMap: getMap,
        getCurrentPower: getCurrentPower,
        exportMap: exportMap
    }, dispatch);
};
export default connect(mapStateToProps, mapDispatchToProps)(MapIndex);
